<template>
  <ArtTableFullScreen>
    <div id="table-full-screen">
      <!-- 搜索栏 -->
      <ArtSearchBar
        v-model:filter="formFilters"
        :items="formItems"
        @reset="handleReset"
        @search="handleSearch"
        :isExpand="true"
      ></ArtSearchBar>
      <el-card shadow="never" class="art-table-card">
        <ArtTableHeader
          :columnList="columnOptions"
          v-model:columns="columnChecks"
          @refresh="handleRefresh"
        >
          <template #left>
            <ElButton v-if="showAdd" :icon="Plus" @click="showDialog('add')">新增</ElButton>
            <ElButton v-else @click="handSure">确定</ElButton>
          </template>
        </ArtTableHeader>
        <!-- 表格 -->
        <art-table
          ref="artTableRef"
          :data="tableData"
          :allData="allTableData"
          :loading="loading"
          v-model:currentPage="queryParams.page"
          v-model:pageSize="queryParams.size"
          :total="total"
          @selection-change="handleSelectionChange"
          @size-change="handleChange"
          @current-change="handleChange"
        >
          <template #default>
            <ElTableColumn v-for="col in columns" :key="col.prop || col.type" v-bind="col" />
            <ElTableColumn
              prop="operation"
              label="操作"
              fixed="right"
              width="220"
              align="center"
              v-if="showAdd"
            >
              <template #default="{ row }">
                <div class="option">
                  <el-button size="small" :icon="Edit" text @click="showDialog('edit', row)"
                    >编辑</el-button
                  >
                  <el-button
                    size="small"
                    type="danger"
                    :icon="Delete"
                    text
                    @click="deleteTableRow(row)"
                    >删除</el-button
                  >
                  <el-button size="small" :icon="View" text @click="showDialog('detail', row)"
                    >详情</el-button
                  >
                </div>
              </template>
            </ElTableColumn>
          </template>
        </art-table>

        <el-dialog
          v-model="dialogVisible"
          :title="dialogType === 'add' ? '添加食物' : '编辑食物'"
          width="40%"
        >
          <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="80px"
            :disabled="disabled"
            @submit.prevent
          >
            <el-form-item label="名称" prop="title">
              <el-input v-model="formData.title" placeholder="请输入食物名称" />
            </el-form-item>
            <el-form-item label="封面" prop="pic">
              <ArtImageUpload v-model:files="formData.pic"></ArtImageUpload>
            </el-form-item>
            <el-form-item label="热量" prop="heat">
              <el-input type="number" v-model="formData.heat" placeholder="请输入食物热量">
                <template #append>卡</template>
              </el-input>
            </el-form-item>
            <el-form-item label="描述" prop="desc">
              <el-input type="textarea" v-model="formData.desc" placeholder="请输入食物描述" />
            </el-form-item>
            <el-form-item label="数量" prop="num">
              <el-input type="number" v-model="formData.num" placeholder="请输入数量" :min="1" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSubmit" :disabled="disabled">提交</el-button>
            </div>
          </template>
        </el-dialog>
      </el-card>
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { FormInstance } from 'element-plus'
  import { ElMessageBox, ElMessage, ElButton } from 'element-plus'
  import { View, Delete, Edit, Plus } from '@element-plus/icons-vue'
  import type { FormRules } from 'element-plus'
  import { useCheckedColumns } from '@/composables/useCheckedColumns'
  import { FoodsService } from '@/api/foods'
  import { SearchChangeParams, SearchFormItem } from '@/types/search-form'
  import ArtImagePreview from '@/components/image/ArtImagePreview.vue'
  import lodash from 'lodash'
  const props = withDefaults(
    defineProps<{
      showAdd?: boolean
      tableRowData?: any
    }>(),
    {
      showAdd: true,
      tableRowData: []
    }
  )
  const emit = defineEmits(['chooseRows'])
  const artTableRef = ref(null)
  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const loading = ref(false)
  const tableData = ref<any>([])
  const allTableData = ref<any>([])
  const disabled = ref(false)
  const formData = reactive({
    title: '',
    pic: '',
    heat: '',
    desc: '',
    num: ''
  })

  const total = ref(0)
  const queryParams = reactive({
    page: 1,
    size: 10,
    title: '' //食物名称
  })
  onMounted(() => {
    getTableData()
  })

  const selectList = ref<any>([])
  watch(
    () => props.tableRowData,
    (newVal) => {
      console.log('newVal', newVal)
      selectList.value = newVal
    },
    { immediate: true }
  )

  // 翻页查询
  const handleChange = () => {
    getTableData()
  }

  const toggleSelection = (rows?: any[]) => {
    nextTick(() => {
      if (rows) {
        rows.forEach((row) => {
          artTableRef.value.tableRef!.toggleRowSelection(row, true)
        })
      } else {
        artTableRef.value.tableRef!.clearSelection()
      }
    })
  }

  //进行数据打√
  const selectTableFun = () => {
    let array: any = []
    tableData.value.forEach((item: any) => {
      selectList.value.forEach((row: any) => {
        if (row.id === item.id) {
          array.push(item)
        }
      })
    })
    toggleSelection(array)
  }

  // 选择项发生变化时触发
  const handleSelectionChange = (rows: any) => {
    console.log('选择项发生变化时触发rows', rows)
    nextTick(() => {
      selectList.value = lodash.uniqWith([...selectList.value, ...rows], lodash.isEqual)
      console.log('selectList', selectList.value)
    })
  }
  // 保存表格数据给父组件
  const handSure = () => {
    if (selectList.value.length === 0) return ElMessage.error('请选择相关食物')
    emit('chooseRows', selectList.value)
    handleReset()
  }
  // 定义表单搜索初始值
  const initialSearchState = {
    title: ''
  }
  // 响应式表单数据
  const formFilters = reactive({ ...initialSearchState })

  // 重置表单
  const handleReset = () => {
    Object.assign(formFilters, { ...initialSearchState })
    queryParams.title = ''
    getTableData()
  }

  // 搜索处理
  const handleSearch = () => {
    queryParams.title = formFilters.title
    getTableData()
  }

  // 表单项变更处理
  const handleFormChange = (params: SearchChangeParams): void => {
    console.log('表单项变更:', params)
  }
  // 表单配置项
  const formItems: SearchFormItem[] = [
    {
      label: '食物名称',
      prop: 'title',
      type: 'input',
      config: {
        clearable: true
      },
      onChange: handleFormChange
    }
  ]
  // 列配置
  const columnOptions = [
    { label: '勾选', type: 'selection' },
    { label: 'ID', prop: 'id' },
    { label: '名称', prop: 'title' },
    { label: '封面', prop: 'pic' },
    { label: '热量', prop: 'heat' },
    { label: '描述', prop: 'desc' },
    { label: '数量', prop: 'num' },
    { label: '创建日期', prop: 'create_time' },
    { label: '操作', prop: 'operation' }
  ]
  // 动态列配置
  const { columnChecks, columns } = useCheckedColumns(() => [
    { type: 'selection' }, // 勾选列
    // { type: 'expand', label: '展开', width: 80 }, // 展开列
    // { type: 'index', label: '序号', width: 80, align: 'center' }, // 序号列
    { prop: 'id', label: 'ID', align: 'center' },
    { prop: 'title', label: '名称', align: 'center' },
    {
      prop: 'pic',
      label: '封面',
      align: 'center',
      formatter: (row: any) => {
        return h(ArtImagePreview, { src: row.pic })
      }
    },
    { prop: 'heat', label: '热量', align: 'center' },
    { prop: 'desc', label: '描述', align: 'center', width: 160 },
    { prop: 'num', label: '数量', align: 'center' },
    {
      prop: 'create_time',
      label: '创建日期',
      align: 'center',
      showOverflowTooltip: true,
      sortable: true
    }
    // {
    //   prop: 'operation',
    //   label: '操作',
    //   width: 220,
    //   align: 'center',
    //   fixed: 'right', // 固定在右侧
    //   formatter: (row: any) => {
    //     return h('div', { class: 'option' }, [
    //       h(
    //         ElButton,
    //         {
    //           size: 'small',
    //           icon: Edit,
    //           text: true,
    //           onClick: () => showDialog('edit', row)
    //         },
    //         () => '编辑'
    //       ),
    //       h(
    //         ElButton,
    //         {
    //           size: 'small',
    //           type: 'danger',
    //           icon: Delete,
    //           text: true,
    //           onClick: () => deleteTableRow(row)
    //         },
    //         () => '删除'
    //       ),
    //       h(
    //         ElButton,
    //         {
    //           size: 'small',
    //           icon: View,
    //           text: true,
    //           onClick: () => showDialog('detail', row)
    //         },
    //         () => '详情'
    //       )
    //     ])
    //   }
    // }
  ])

  // 获取商品列表
  const getTableData = async () => {
    loading.value = true
    const res = await FoodsService.getFoodsSourceList(queryParams)
    total.value = res.data.total
    loading.value = false
    tableData.value = res.data.data
    selectTableFun()
  }
  // 刷新
  const handleRefresh = () => {
    getTableData()
  }
  const setFromData = (row: any) => {
    formData.title = row.title
    formData.pic = row.pic
    formData.heat = row.heat
    formData.desc = row.desc
    formData.num = row.num
    formData.id = row.id
  }
  const resetFromData = () => {
    formData.title = ''
    formData.heat = ''
    formData.desc = ''
    formData.pic = ''
    formData.num = ''
    formData.id = null
  }
  // 显示弹窗
  const showDialog = (type: string, row?: any) => {
    disabled.value = false
    if (type === 'edit' && row) {
      setFromData(row)
    } else if (type === 'detail' && row) {
      setFromData(row)
      disabled.value = true
    } else {
      resetFromData()
    }
    dialogVisible.value = true
    dialogType.value = type
  }
  const deleteTableRow = (row: any) => {
    ElMessageBox.confirm('确定要删除该列吗？', '删除列表', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    })
      .then(() => {
        return FoodsService.delFoodsSource(row.id)
      })
      .then(() => {
        getTableData()
        ElMessage.success('删除成功')
      })
  }

  const rules = reactive<FormRules>({
    title: [{ required: true, message: '请输入食物名称', trigger: 'blur' }],
    pic: [{ required: true, message: '请选择食物封面', trigger: 'blur' }],
    heat: [{ required: true, message: '请输入食物热量', trigger: 'blur' }],
    // num: [{ required: true, message: '请输入食物数量', trigger: 'blur' }],
    desc: [{ required: true, message: '请输入食物描述', trigger: 'blur' }]
  })

  const formRef = ref<FormInstance>()

  const handleSubmit = () => {
    if (!formRef.value) return
    formRef.value.validate(async (valid) => {
      if (valid) {
        if (dialogType.value === 'add') {
          await FoodsService.addFoodsSource(formData)
        } else {
          await FoodsService.updateFoodsSource(formData)
        }
        await getTableData()
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        dialogVisible.value = false
      }
    })
  }

  defineExpose({
    clearSelection: () => {
      artTableRef.value.clearSelection()
    }
  })
</script>

<style lang="scss" scoped>
  :deep(.option .el-button + .el-button) {
    margin-left: 0;
  }
</style>
